package com.liang.pcc.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson2.JSON;
import com.liang.pcc.common.result.Result;
import com.liang.pcc.common.result.Results;
import com.liang.pcc.domain.EvaluationHistory;
import com.liang.pcc.domain.HarmonicData;
import com.liang.pcc.domain.MeasurementPointDO;
import com.liang.pcc.dto.resp.*;
import com.liang.pcc.mapper.DataMapper;
import com.liang.pcc.mapper.MeasurementPointMapper;
import com.liang.pcc.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/data")
@RequiredArgsConstructor
public class DataController {

    private final DataMapper dataMapper;
    private final ShortCircuitCurrentVerificationService shortCircuitService;
    private final VoltageDeviationCheckService voltageDeviationService;
    private final HarmonicDataService harmonicDataService;
    private final ExcelFileService excelFileService;
    private final EvaluationHistoryService evaluationHistoryService;
    private final MeasurementPointMapper measurementPointMapper;
    private final AuthUserService authUserService;

    /**
     * 获取当前用户上传的文件
     */
    @GetMapping("file")
    public Result<List<String>> getFileList() {
        return Results.success(excelFileService.getFileList());
    }

    /**
     * 反向负载率
     */
    @GetMapping("reverse-load-rate")
    public Result<List<ReverseLoadRateResp>> getReverseLoadRate(@RequestParam(required = false) String fileName) {
        Long fileId = excelFileService.getFileId(fileName);
        Long userId = getUserId();
        List<ReverseLoadRateResp> res = dataMapper.getReverseLoadRate(fileId, userId);
        return Results.success(res);
    }

    /**
     * 短路电流校核
     */
    @GetMapping("short-circuit")
    public Result<List<ShortCircuitCurrentVerification>> getShortCircuit(@RequestParam(required = false) String fileName) {
        Long fileId = excelFileService.getFileId(fileName);
        List<ShortCircuitCurrentVerification> res = shortCircuitService.getShortCircuitByFile(fileId);
        return Results.success(res);
    }

    /**
     * 电压偏差校核
     */
    @GetMapping("voltage-deviation")
    public Result<List<VoltageDeviationCheck>> getVoltageDeviation(@RequestParam(required = false) String fileName) {
        Long fileId = excelFileService.getFileId(fileName);
        List<VoltageDeviationCheck> res = voltageDeviationService.getVoltageDeviationByFile(fileId);
        return Results.success(res);
    }

    /**
     * 谐波电流
     */
    @GetMapping("harmonic-current")
    public Result<List<HarmonicCurrentResp>> getHarmonicCurrent(@RequestParam(required = false) String fileName) {
        Long fileId = excelFileService.getFileId(fileName);
        List<HarmonicCurrentResp> res = new ArrayList<>();
        Long userId = getUserId();
        List<MeasurementPointDO> measurementPoints = measurementPointMapper.selectAll(fileId, userId);
        log.info("实测点：{}", JSON.toJSONString(measurementPoints));
        measurementPoints.forEach(item -> {
            List<HarmonicData> harmonicData = harmonicDataService.getHarmonicData(fileId, item.getId());
            HarmonicCurrentResp resp = HarmonicCurrentResp.builder()
                    .id(item.getId())
                    .pointName(item.getPointName())
                    .voltageLevel(item.getVoltageLevel())
                    .shortCircuitCapacity(item.getShortCircuitCapacity())
                    .harmonics(harmonicData)
                    .build();
            res.add(resp);
            log.info("实测点数据：{}", JSON.toJSONString(item));
        });
        return Results.success(res);
    }

    /**
     * 光伏承载力评估
     */
    @GetMapping("evaluate")
    public Result<List<EvaluationHistory>> getEvaluationHistory(@RequestParam(required = false) String fileName) {
        Long fileId = excelFileService.getFileId(fileName);
        evaluationHistoryService.lambdaUpdate()
                .set(EvaluationHistory::getUserAccount, StpUtil.getLoginId())
                .update();
        List<EvaluationHistory> res = evaluationHistoryService.getEvaluationHistory(fileId);
        return Results.success(res);
    }

    /**
     * 获取整合数据
     */
    @GetMapping("integration")
    public Result<List<IntegrationDataResp>> getIntegrationData(@RequestParam(required = false) String fileName) {
        Long fileId = excelFileService.getFileId(fileName);
        Long userId = getUserId();
        List<IntegrationDataResp> res = dataMapper.getIntegrationData(fileId, userId);
        return Results.success(res);
    }

    /**
     * 删除同名文件的所有数据
     */
    @DeleteMapping("remove")
    public Result<Void> remove(@RequestParam String fileName) {
        Long userId = getUserId();
        Long fileId = excelFileService.getFileId(fileName);
        dataMapper.removeBusParam(fileId, userId);
        dataMapper.removeDeviceInfo(fileId, userId);
        dataMapper.removeEquipmentLineInfo(fileId, userId);
        dataMapper.removeEvaluationHistory(fileId, userId);
        dataMapper.removeHarmonicData(fileId, userId);
        dataMapper.removeMeasurementPoint(fileId, userId);
        dataMapper.removePowerData(fileId, userId);
        dataMapper.removeShortCircuitCurrentVerification(fileId, userId);
        dataMapper.removeTopologyData(fileId, userId);
        dataMapper.removeVoltageDeviationCheck(fileId, userId);
        excelFileService.removeById(fileId);
        return Results.success("删除成功");
    }

    private Long getUserId() {
        return authUserService.getUserIdByAccount(StpUtil.getLoginId().toString());
    }
}
